package com.duoec.dw.lineage.service.analyser.statement;

import com.duoec.dw.lineage.dto.SqoopCommendArgument;
import com.duoec.dw.lineage.dto.statement.DropSqoopStatement;
import com.duoec.dw.lineage.dto.statement.SqoopStatement;
import com.duoec.dw.lineage.dto.statement.TruncateTableSqoopStatement;
import com.duoec.dw.lineage.exceptions.LineageAnalyseException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xuwenzhen
 */
@Service
public class EvalSqoopStatementAnalyser extends BaseSqoopStatementAnalyser<SqoopStatement> {

    public static final String STR_EVAL = "eval";
    public static final String STR_DROP_PARTITION = "DROP_PARTITION";
    public static final String STR_TRUNCATE = "TRUNCATE";
    public static final String STR_DELETE = "DELETE";

    /**
     * 检查当前行是否需要当前分析器处理
     *
     * @param line 当前行
     * @return true，则会使用analyse方法解析
     */
    @Override
    public boolean check(String line) {
        return line.startsWith(STR_EVAL);
    }

    /**
     * 解析脚本，并返回当前的语句
     *
     * @param lines 所有行
     * @param index 开始行，0开始
     * @return 当前语句
     */
    @Override
    public SqoopStatement analyse(List<String> lines, int index) {
        String line = lines.get(index);
        SqoopCommendArgument args = getArgument(line);
        String query = args.getQuery().toUpperCase();
        if (query.contains(STR_DROP_PARTITION)) {
            // SELECT	DROP_PARTITION('duoec_second_house_edw_source.s_du_t_second_agent_groupsend_delta','${dt}')
            // 删除分区
            DropSqoopStatement statement = new DropSqoopStatement();
            statement.setStart(index);
            statement.setEnd(index);
            statement.setSql(query);
            return statement;
        } else if (query.contains(STR_TRUNCATE) || query.contains(STR_DELETE)) {
            // 清除表数据
            TruncateTableSqoopStatement statement = new TruncateTableSqoopStatement();
            statement.setStart(index);
            statement.setEnd(index);
            statement.setSql(query);
            return statement;
        } else {
            throw new LineageAnalyseException("无法解析：" + line);
        }
    }
}
